const $ = require("../ThirdParty/jquery.js");
const currentWindow = require("electron").remote.getCurrentWindow();
const BrowserWindow = require("electron").remote.BrowserWindow;
const dialog = require("electron").remote.dialog;
const session = require("electron").remote.session;
const fs = require("fs");
const path = require("path");
const shell = require("electron").remote.shell;
const storage = require("electron-json-storage");

window.nodeRequire = require;
delete window.require;
delete window.exports;
delete window.module;

var markdownFileData;
var isMarkdownFileChanged = false;
// render window buttons
$("body")
  .append(`<div class="min_button" onclick="minApp();"><i class="fa fa-minus"></i></div>
<div class="max_button" onclick="maxApp();"><i class="far fa-square"></i></div>
<div class="close_button" onclick="closeApp();"><i class="fa fa-times"></i></div>`);

// load bootstrap and jquery
$("body").append(`<script src="../ThirdParty/jquery.js"></script>
<script src="../ThirdParty/bootstrap.bundle.js"></script>
<script src="../ThirdParty/marked.js"></script>`);

const render_nav = () => {
  $.ajax({
    method: "GET",
    url: "./app.json",
    success: function (data) {
      let NavigationData = new Object();
      NavigationData.apptitle = data.title;
      NavigationData.sectionList = data.index;
      let Navigation = `
        <div class="navbar navbar-expand navbar-light bg-light">
            <a class="navbar-brand" id="navTitle" href="#">${NavigationData.apptitle}</a>
              <ul id="sectionList" class="navbar-nav ">
              </ul>
        </div>
        `;

      $("nav").append(Navigation);
      for (var i = 0; i < NavigationData.sectionList.length; i++) {
        $("#sectionList").append(`
            <li class="nav-item" id="${
              NavigationData.sectionList[i].id + "Nav"
            }">
            <a class="nav-link" href="./${
              NavigationData.sectionList[i].id + ".html"
            }">${NavigationData.sectionList[i].name}</a>
            </li>`);
        if (
          window.location.href.indexOf(
            NavigationData.sectionList[i].id + ".html"
          ) != -1
        ) {
          $("#" + NavigationData.sectionList[i].id + "Nav").attr(
            "class",
            "active"
          );
        }
      }

      if ($("#sectionList").html().indexOf("active") == -1) {
        $("#sectionList").html("");
      }
    },
  });
};
// 关闭，还原/最大化，最小化（右上角的三个按钮）

let minApp = () => {
  currentWindow.minimize();
};

let maxApp = () => {
  if (currentWindow.isMaximized() === false) {
    currentWindow.maximize();
  } else {
    currentWindow.restore();
  }
};

let closeApp = () => {
  if (isMarkdownFileChanged !== false) {
    // 文件被编辑，不应该直接关闭程序。或导致数据丢失。
    ifWannaSaveFileDialogClose.show();
  } else {
    currentWindow.destroy();
  }
};

render_nav();

let openMarkdownFile = new Object();

openMarkdownFile.outsideEditorStageStart = () => {
  $("#markdownFileSelector").click();
};

openMarkdownFile.outsideEditorStageSelected = () => {
  let markdownFilePath = document.querySelector("#markdownFileSelector")
    .files[0].path;
  window.location.href = "./editor.html?filepath=" + markdownFilePath;
};

openMarkdownFile.stageStart = () => {
  $("#markdownFileSelector").click();
};

openMarkdownFile.stageSelected = () => {
  if ($("#editor_writing").val() !== "") {
    // 编辑器有内容时，在新窗口打开文件
    let markdownFilePath = document.querySelector("#markdownFileSelector")
      .files[0].path;

    let new_win_b = new BrowserWindow({
      width: 1000,
      height: 600,
      webPreferences: {
        nodeIntegration: true,
        enableRemoteModule: true,
      },
      frame: false,
    });

    new_win_b.loadURL(
      "file://" + __dirname + "/editor.html?filepath=" + markdownFilePath
    );

    new_win_b.on("close", (e) => {
      e.preventDefault();
    });
  } else {
    let markdownFilePath = document.querySelector("#markdownFileSelector")
      .files[0].path;
    fs.readFile(markdownFilePath, "utf8", function (err, data) {
      document.querySelector("#editor_writing").value = data;
      markdown_preview();
    });
    $("#markdownFileName").text(path.basename(markdownFilePath));
    markdownEditorFilePath = markdownFilePath;
  }

  document.querySelector("#markdownFileSelector").value=""
};

function getUrlArgs(variable) {
  var query = window.location.search.substring(1);
  var vars = query.split("&");
  for (var i = 0; i < vars.length; i++) {
    var pair = vars[i].split("=");
    if (pair[0] == variable) {
      return pair[1];
    }
  }
  return false;
}

let saveMarkdownFile = () => {
  if (markdownEditorFilePath !== undefined) {
    fs.writeFileSync(markdownEditorFilePath, $("#editor_writing").val());
    alert("已经保存。");
    $("#markdownFileChanged").html("");
    isMarkdownFileChanged = false;
  } else {
    saveAsMarkdownFile();
  }
};

let saveAsMarkdownFile = () => {
  let saveAsPath = dialog.showSaveDialogSync();
  if (saveAsPath !== undefined) {
    console.log(saveAsPath);
    fs.writeFileSync(saveAsPath, $("#editor_writing").val());
    markdownEditorFilePath = saveAsPath;
    $("#markdownFileName").text(path.basename(saveAsPath));
    $("#markdownFileChanged").html("");
    isMarkdownFileChanged = false;
  }
};

function ifWannaSaveFileDialogClose_save() {
  saveMarkdownFile();
  if (markdownEditorFilePath !== undefined) {
    currentWindow.destroy();
  }
}

function ifWannaSaveFileDialogClose_dontsave() {
  currentWindow.destroy();
}

function ifWannaSaveFileDialogClose_cancel() {
  ifWannaSaveFileDialogClose.hide();
}

// back main page

function clickBackMainPageBtn() {
  if (isMarkdownFileChanged === true) {
    ifWannaSaveFileDialogBackMainPage.show();
  } else {
    window.location.href = "./start.html";
  }
}

function ifWannaSaveFileDialogBackMainPage_save() {
  saveMarkdownFile();
  if (markdownEditorFilePath !== undefined) {
    window.location.href = "./start.html";
  }
}

function ifWannaSaveFileDialogBackMainPage_dontsave() {
  window.location.href = "./start.html";
}

function ifWannaSaveFileDialogBackMainPage_cancel() {
  ifWannaSaveFileDialogBackMainPage.hide();
}

var not_finished_function = () => {
  alert("此功能在当前版本未实现，请期待以后的版本。");
};

//配色方案

let whiteWindowButton = () => {
  $(".min_button").css("color", "white");
  $(".max_button").css("color", "white");
  $(".close_button").css("color", "white");
};

let darkenNavBar = () => {
  $(".navbar").attr("class", "navbar navbar-expand navbar-dark bg-dark");
};

let colorToNavBar = (colorName) => {
  $(".navbar").attr("style", "background-color:" + colorName + "!important");
};

let colorToBody = (colorName) => {
  $("body").css("background-color", colorName);
  $("#editor_writing").css("background-color", colorName);
};

// 配色方案（皮肤）
storage.has("skin", function (error, hasKey) {
  if (error) throw error;

  if (hasKey) {
    storage.get("skin", function (error, data) {
      if (error) throw error;

      var skin = data.skin;
      switch (skin) {
        case "light":
          break;
        case "dark":
          darkenNavBar();
          whiteWindowButton();
          colorToBody("whitesmoke");
          break;
        case "cyan":
          darkenNavBar();
          whiteWindowButton();
          colorToNavBar("#087990");
          colorToBody("#cfe2ff");
          break;
        case "sakura":
          darkenNavBar();
          whiteWindowButton();
          colorToNavBar("#de5c9d");
          colorToBody("#f7d6e6");
          break;
        case "teal":
          darkenNavBar();
          whiteWindowButton();
          colorToNavBar("#20c997");
          colorToBody("#d2f4ea");
          break;
        case "red":
          darkenNavBar();
          whiteWindowButton();
          colorToNavBar("#dc3545");
          colorToBody("#f8d7da");
          break;
        case "lemon":
          whiteWindowButton();
          colorToNavBar("#ffc107");
          colorToBody("#fff3cd");
          break;
        case "indigo":
          darkenNavBar();
          whiteWindowButton();
          colorToNavBar("#3d0a91");
          colorToBody("#e0cffc");
          break;
        case "autumn":
          whiteWindowButton();
          darkenNavBar();
          colorToNavBar("#ca6510");
          colorToBody("#ffe5d0");
          break;
      }
    });
  } else {
    storage.set("skin", { skin: "light" }, function (err) {
      window.location.reload();
    });
  }
});

let selectFolderAsNotebook = () => {
  let notebookDir = dialog.showOpenDialogSync({
    properties: ["openDirectory"],
  });
  if (notebookDir !== undefined) {
    window.location.href = "./notebook.html?path=" + notebookDir;
  }
};

let clickBackMainPageBtnNotebook = () => {
  window.location.href = "./start.html";
};

let showTPLN = ()=>{
  // Third Party Legal Notices
  $.ajax({
    method: "GET",
    url: "../Third_Party_Legal_Notices.md",
    success: (data) => {
      window.alert(data);
    },
  });
  

}